package com.example.java_gobang.service;

import com.example.java_gobang.mapper.UserMapper;
import com.example.java_gobang.model.User;
import com.example.java_gobang.tools.Constant;
import com.example.java_gobang.tools.ResponseBodyMessage;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2022-08-15
 * Time: 11:29
 */
@Service
public class UserService {
    @Resource
    private UserMapper userMapper;

    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    public ResponseBodyMessage<User> userLogin(HttpServletRequest request, @RequestParam String username, @RequestParam String password){
        User user = userMapper.selectByName(username);
        HttpSession session = request.getSession(true);
        if(user != null){
            String userPassword = user.getPassword();
            boolean flg = bCryptPasswordEncoder.matches(password,userPassword);

            System.out.println(userPassword);
            if(flg){
                session.setAttribute(Constant.USERINFO_SESSION_KEY,user);
                user.setPassword(null);
                return new ResponseBodyMessage<>(0,"登录成功",user);
            }else{
                return new ResponseBodyMessage<>(-1,"登录失败",null);
            }

        }else{
            return new ResponseBodyMessage<>(-1,"当前用户不存在",null);
        }
    }

    public ResponseBodyMessage<User> userRegister(@RequestParam String username, @RequestParam String password){
        User user = userMapper.selectByName(username);

        if(user == null){
            User user1 = new User();
            user1.setUsername(username);
            String newPassword = bCryptPasswordEncoder.encode(password);
            user1.setPassword(newPassword);

            int ret = userMapper.insert(user1);

            if(ret == 1){
                user1.setPassword(null);
                return new ResponseBodyMessage<>(0,"注册成功",user1);
            }else{
                return new ResponseBodyMessage<>(-1,"注册失败",null);
            }
        }else{
            return new ResponseBodyMessage<>(-1,"当前用户存在",null);
        }
    }

    public ResponseBodyMessage<User> getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null){
            return new ResponseBodyMessage<>(-1,"当前尚未登录",null);
        }
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        User newUser = userMapper.selectByName(user.getUsername());
        return new ResponseBodyMessage<>(0,"成功获取用户信息",newUser);
    }
}
